<%-- 
  - Author: Asna Khader
  - Date: 02-Mar-2012
  - Copyright Notice: TRAKHEES
  - Description: form.jsp
 --%>
<%@ page import="ae.pcfc.etks.cld.to.web.Constants" %>
<%@ include file="/WEB-INF/view/include.jsp"%>
    <div>
    	<div id="tabs">
	      <ul id="TabHeader">
	        <li><a href="#VisitVisaDetails"><spring:message code="header.visitvisa_details" /></a></li>
	        <li><a href="#PersonalDetails"><spring:message code="header.personal_details" /></a></li>
	         <li><a href="#Comments"><spring:message code="header.comments" /></a></li>
	        <li><a href="#Attachments"><spring:message code="header.attachments" /></a></li>
	        <li><a href="#Summary"><spring:message code="header.summary" /></a></li>
	      </ul>
	          <spring:hasBindErrors
						name="filesIncomingBean">
								<script type="text/javascript">
								$(document).ready(
										function() {
											jAlert('error', '<li><div style="color:red;"><spring:message code="${errors.allErrors[0].code}" text="${errors.allErrors[0].defaultMessage}"/></div></li>',
													'<spring:message code="label.errormessage" />');
										});
								</script>
		    </spring:hasBindErrors>
	      
	      <form:form modelAttribute="VisitVisaLicenseInfo" name="VisitVisaFrm"  id="VisitVisaFrm"  method="POST" enctype="multipart/form-data" class="t_form">
	      		<spring:hasBindErrors
						name="VisitVisaLicenseInfo">
							<script type="text/javascript">
								$(document).ready(
										function() {
											jAlert('error', '<li><form:errors path="*" delimiter="<li>"/>',
													'<spring:message code="label.errormessage" />');
										});
					</script>
		    </spring:hasBindErrors>
				<%@include file="VisitVisaDetailsTab.jsp" %>
				<%@include file="PersonalDetailsTab.jsp" %>
				<%@include file="CommentsTab.jsp" %>
				<%@include file="AttachmentsTab.jsp" %>
				<%@include file="SummaryTab.jsp" %>
				
				
				<div id="FNPPaymentInfoTab" class="t_pop_up"> 
	        	  <%@include file="../../../admin/general/payment/PaymentInfoTab.jsp" %>
	        	</div>
				
				<c:if test="${isResubmit}">
					<input type="hidden" name="isResubmit" value="${isResubmit}">
					<input type="hidden" name="appId" value="${appId}">
				</c:if>
			
			<c:choose>
				<c:when	test='${requestScope.requestContextAttribute.locale.language == "ar"}'>
					<a id="termsAndConditionLink" href="resources/staticContents/termsAndConditions/visitVisa/visitTermsAndCondition_ar.jsp" style="display:none; ">terms and condition</a>
				</c:when>
				<c:otherwise>
					<a id="termsAndConditionLink" href="resources/staticContents/termsAndConditions/visitVisa/visitTermsAndCondition_en.jsp" style="display:none; ">terms and condition</a>
				</c:otherwise>
			</c:choose>
				
		 </form:form>
	      
       </div>
    </div>
    <!--Middle Right Close-->
<script>
        var $tabs ;
    
		//Validation - Required fields
		$().ready(function() {
			
			
			$("#termsAndConditionLink").fancybox({
				'width'				: '60%',
				'height'			: '30%',
		        'autoScale'     	: false,
		        'transitionIn'		: 'none',
				'transitionOut'		: 'none',
				'type'				: 'iframe',
				'modal'				:'true'
			});
			
			var checkTrmsAndCondsCookie = $.cookie('vvtrmsconds');
			
			if(checkTrmsAndCondsCookie == null){
				$("#termsAndConditionLink").trigger('click');
			}
		
			$(".topnav").accordion({
				accordion:false,
				speed: 500,
				closedSign: '<img src=\'resources/images/common/close.jpg\' />',
				openedSign: '<img src=\'resources/images/common/open.jpg\' />'
			});
			$( "#VisitVisaDetails #lastEntryDate, #PersonalDetails #issueDate,#PersonalDetails #expiryDate,#PersonalDetails #dateOfBirth" ).datepicker({
				showOn: "button",
				buttonImage: "resources/images/calender.jpg",
				dateFormat : 'dd/mm/yy',
				buttonImageOnly: true,
				changeMonth:true,
				changeYear:true,
				minDate: new Date(1900,1 - 1 ,1),
				yearRange:'c-50:c+10'
			});

		 	$.validator.addMethod(
			        "regex",
			        function(value, element, regexp) {
			            
			            var re = new RegExp(regexp);
			            return this.optional(element) || re.test(value);
			        }
				);
	    	
	    	$.validator.addMethod(
					"pastDate", 
					function(value, element) {
						if(value!=null && value!=''){
							var datePast = new Date(formatDate(value));
	        				var today = new Date();
	        				return (datePast < today);
						}else{
							return true;
						}
		        				
		   		 });
	    	$.validator.addMethod(
					"dateFormatValid", 
					function(value, element) {
						if(value!=null && value!=''){
		        				return !!Date.parseExact(value, 'dd/MM/yyyy');
						}else{
							return true;
						}
		    });

	     	$.validator.addMethod(
					"pastDateDOB", 
					function() {
								var dateOfBirth = new Date(formatDate($("#dateOfBirth").val()));
		        				var today = new Date();
		        				return (dateOfBirth < today);
		   		 });
	     	$.validator.addMethod(
					"DOBlessthanPassport", 
					function() {
								var dateOfBirth = new Date(formatDate($("#dateOfBirth").val()));
								var pprtDate = new Date(formatDate($("#issueDate").val()));
		        				return (dateOfBirth < pprtDate);
		   		 });
	
	    	$.validator.addMethod(
					"passportExpiryDate", 
					function() {
		        				var expiryDate = new Date(formatDate($("#expiryDate").val()));
		        				var sixMonthFromNow = new Date();
		        				sixMonthFromNow.setMonth(sixMonthFromNow.getMonth() +6);
		        				return ( expiryDate >= sixMonthFromNow);
		    });
	     	$.validator.addMethod(
			        "upperRegex",
			        function(value, element, regexp) {
			        	var flag = (/[a-z]/.test(value));
			            return !flag;
			        }
				);

		 	$("#VisitVisaFrm").validate({
				onfocusout:false,
				onkeyup:false,
				onclick: false,			
				rules : {
					//Employee Details
					strNameInPassport : {
						 required :true,
						 upperRegex: "/[a-z]/" 
					},
					strPriority: "required",
					lastEntryPort:"required",
					strGender : "required",
					strNationality: "required",
					strMaritalStatus: "required",
					//Passport Details
					strPassportNo : {
						 required :true,
						 upperRegex: "/[a-z]/" 
					},
					issueDate: {
						required : true,
						pastDate: true,
						dateFormatValid : true,
						DOBlessthanPassport : true
					},
					expiryDate: {// compound rule
						required : true,
						passportExpiryDate:true,
						dateFormatValid : true
					},
					dateOfBirth: {// compound rule
						required : true,
						dateFormatValid : true,
						pastDate:true
					},	
					lastEntryDate: {// compound rule
						required : false,
						dateFormatValid : true,
						pastDate:true
					},
					
					strCityOfIssue: "required",
					//Personal Details
					strFatherName: "required",
					strMotherName: "required",
					strFamilyName: "required",
					strFatherNameArb: "required",
					strFamilyNameArb: "required",
					strMotherNameArb: "required",
					strBirthPlace: "required",
					qualification: "required",
					spokenLanguage1: "required",
					//Address Details
					strAddressAbroad: "required",
					strPreviousNationality: "required"
				
						//Attachments
						<c:if test="${!isResubmit}">,passportCopy : "required", letterFromCompany : "required", photograph : "required"</c:if>
				},
				
				submitHandler: function (form) {
					blockPage();
					form.submit();
				},
				
				showErrors : function(errorMap, errorList) {
					
					var errors = '<ul>';
					var label;				
					if (errorList.length) {
						$.each(errorMap, function(name, value) {
							label = $("label[for='" + name + "']").html();
							label = value + '[' + label + ']';
							errors = errors + '<li>' + label + '</li>';
							

						});
						errors = errors + '</ul>';
						jAlert('error', errors, '<spring:message code="label.errormessage" />');
						return false;
					}
				}		
			});

			$tabs = $("#tabs").tabs();	
			$('#TabHeader').removeClass('ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all');
			$('#TabHeader > li').removeClass('ui-state-default ui-corner-top ui-state-active ui-state-hover');
			$('#tabs').removeClass('ui-widget ui-widget-content ui-corner-all');
			
			$('#tabs').tabs({
				select : function(event, ui) {
					
					var selected = $tabs.tabs('option', 'selected'); // => 0
					var clicked = ui.index; // => 0
										
					if( selected > clicked )
						return true;
					
					var isValid = validate(clicked);// form validation returning true or false
					
					if(clicked == 4){
						updateSummaryTab();
					}
					return isValid;
				}
			});
			
	
			$('#VisitVisaDetails-Next').click(function() { // bind click event to link			
				$tabs.tabs('select', 1);
				return false;
				//$('#VisitVisaFrm').submit();
			});
		
			$('#VVPersonalDetails-Next').click(function() { // bind click event to link			
				$tabs.tabs('select', 2);
				return false;
			});
			
			$('#Comments-Next').click(function() { // bind click event to link			
				$tabs.tabs('select', 3);
				return false;
			});
			$('#VVAttachments-Next').click(function() { // bind click event to link			
				$tabs.tabs('select', 4);
				return false;
			});
			
			//Prev Buttons
			
			
			$('#VVPersonalDetails-Prev').click(function() { // bind click event to link			
				$tabs.tabs('select', 0);
				return false;
			});
			$('#VVAttachments-Prev').click(function() { // bind click event to link			
				$tabs.tabs('select', 2);
				return false;
			});
			$('#Comments-Prev').click(function() { // bind click event to link			
				$tabs.tabs('select', 1);
				return false;
			});
			
			//CLOSING POPUP
				//Click the x event!
				$("#popupContactClose").click(function(){
					disablePopup();
				});
				//Click out event!
				$("#backgroundPopup").click(function(){
					disablePopup();
				});
				//Press Escape event!
				$(document).keypress(function(e){
					if(e.keyCode==27 && popupStatus==1){
						disablePopup();
					}
				});
		});	
		
		function submitForm(divId){
			if(validate(6)){
				$('#VisitVisaFrm').append($("#"+divId).html());
				var input = $("<input>").attr("type", "hidden").attr("name", "submitted").val("submitted");
				$('#VisitVisaFrm').append($(input));
				$.fancybox.showLoading();
				$('#VisitVisaFrm').submit();
			} else {
				return false;
			}
		}
		
		function validate(clicked) {
			//var selected = $tabs.tabs('option', 'selected'); // => 0		
			var result = true;
			
			if(clicked > 0)
			{
				result =  (
						$("#VisitVisaFrm").validate().element("#strPriority") 
						&& $("#VisitVisaFrm").validate().element("#lastEntryDate") 
						&& $("#VisitVisaFrm").validate().element("#lastEntryPort") 
						);
			}
			if(clicked > 1)
			{
				result = result && (
						$("#VisitVisaFrm").validate().element("#strNameInPassport")
						&& $("#VisitVisaFrm").validate().element("#strPassportNo") 
						&& $("#VisitVisaFrm").validate().element("#issueDate")
						&& $("#VisitVisaFrm").validate().element("#expiryDate")
						&& $("#VisitVisaFrm").validate().element("#strCityOfIssue")
						&& $("#VisitVisaFrm").validate().element("#strFatherName") 
						&& $("#VisitVisaFrm").validate().element("#strMotherName")
						&& $("#VisitVisaFrm").validate().element("#strFamilyName") 
						&& $("#VisitVisaFrm").validate().element("#strFamilyNameArb")
						&& $("#VisitVisaFrm").validate().element("#strFatherNameArb") 
						&& $("#VisitVisaFrm").validate().element("#strMotherNameArb")
						&& $("#VisitVisaFrm").validate().element("#dateOfBirth")
						&& $("#VisitVisaFrm").validate().element("#strBirthPlace")
						&& $("#VisitVisaFrm").validate().element("#strGender")
						&& $("#VisitVisaFrm").validate().element("#strMaritalStatus")
						&& $("#VisitVisaFrm").validate().element("#qualification")
						&& $("#VisitVisaFrm").validate().element("#strNationality")
						&& $("#VisitVisaFrm").validate().element("#spokenLanguage1")
						&& $("#VisitVisaFrm").validate().element("#strAddressAbroad")
						&& $("#VisitVisaFrm").validate().element("#strPreviousNationality")
						
						);
			}
			if(clicked > 3)
			{
				result = result && (
						$("#VisitVisaFrm").validate().element("#PassportCopy")
						&& $("#VisitVisaFrm").validate().element("#LetterFromCompany")
						&& $("#VisitVisaFrm").validate().element("#Photograph")
						
				);
			}
			
			return result;
			
		}
		
		function validatePayment() {
			return ($("#VisitVisaFrm").validate().element("#fnpServiceCode"));
		}
		

		 var addressFormatting = function(text){
			var newText = text;
			//array of find replaces
			var findreps = [
				{find:/^([^\-]+) \- /g, rep: '<span class="ui-selectmenu-item-header">$1</span>'},
				{find:/([^\|><]+) \| /g, rep: '<span class="ui-selectmenu-item-content">$1</span>'},
				{find:/([^\|><\(\)]+) (\()/g, rep: '<span class="ui-selectmenu-item-content">$1</span>$2'},
				{find:/([^\|><\(\)]+)$/g, rep: '<span class="ui-selectmenu-item-content">$1</span>'},
				{find:/(\([^\|><]+\))$/g, rep: '<span class="ui-selectmenu-item-footer">$1</span>'}
			];
			
			for(var i in findreps){
				newText = newText.replace(findreps[i].find, findreps[i].rep);
			}
			return newText;
		}
		
		function updateSummaryTab(){
		
			
			if($.browser.msie && $.browser.version.substr(0,1)<7){
				$("#VisitVisaFrm input[type=hidden]").each(function() {	
		       		$('#Summary input#sum'+$(this).attr('id')).val($("#cuselFrame-"+$(this).attr('id')+" .cuselText").html());
		       		$('#Summary input#sum'+$(this).attr('id')).attr('disabled', true);
		
		    	});
			}
			
		  	$("#VisitVisaFrm input[type=text]").each(function() {

		       		$('#Summary input#sum'+$(this).attr('id')).val(this.value);
		       		$('#Summary input#sum'+$(this).attr('id')).attr('disabled', true);

		    });
		    
		    $("#VisitVisaFrm select").each(function() {
		       		
		       		$('#Summary input#sum'+$(this).attr('id')).val($('#VisitVisaFrm select#'+$(this).attr('id')+ ' option:selected').text());
		       		$('#Summary input#sum'+$(this).attr('id')).attr('disabled', true);

		    });
		    
		    $("#VisitVisaFrm input[type=file]").each(function() {
		    	if(this.value != null && this.value != ''){
		    		$('#Summary input#sum'+$(this).attr('id')).val(this.value);
		    	} else {
		    		$('#Summary input#sum'+$(this).attr('id')).val($('#prev'+$(this).attr('id')).html());
		    	}
		       	$('#Summary input#sum'+$(this).attr('id')).attr('disabled', true);

		    });
		    
		    $("#VisitVisaFrm textarea").each(function() {

				$('#Summary textarea#sum'+$(this).attr('id')).val($(this).val());
	       		$('#Summary textarea#sum'+$(this).attr('id')).attr('disabled', true);

		    });
		    
		    <c:if test="${isCompanyAdmin}">
		    	$('#fnpServiceCode').rules("add", { required: true });
		    </c:if>
		}
</script>